#!/bin/bash

make_sure_dir_exist () { [ -d $1 ] || mkdir -p $1;}

echo "Running [$PROJECT_NAME] environment forever"
forever () {
    while [ 1 ]
    do
        # make nginx run forever
        if [[ `ps aux | grep nginx | grep master | wc -l` -lt 1 ]]; then
            /usr/sbin/nginx -c /opt/etc/nginx.conf &
        fi
        # make gunicorn run forever
        if [ "$DEBUG" == "True" ]; then
            if [[ `ps aux | grep manage.py | wc -l` -lt 2 ]]; then
                python manage.py runserver 0.0.0.0:8000 &
            fi
        else
            if [[ `ps aux | grep gunicorn | grep python | wc -l` -lt 1 ]]; then
                /usr/local/bin/gunicorn -c /opt/etc/gunicorn_conf.py wsgi &
            fi
        fi
        sleep 3
    done
}

# make sure dir is exist
make_sure_dir_exist "/opt/log/nginx"
make_sure_dir_exist "/opt/log/gunicorn"
make_sure_dir_exist "/opt/log/os_stdout"
make_sure_dir_exist "/opt/log/os_stderr"

# out put system log
NOW=$(date +%Y-%m-%d-%H-%M-%S)
forever > "/opt/log/os_stdout/$NOW.log" 2> "/opt/log/os_stderr/$NOW.log"
